package com.yeb.server.controller;


import com.yeb.server.pojo.Admin;
import com.yeb.server.service.IAdminService;
import com.yeb.server.vo.AdminLoginParam;
import com.yeb.server.vo.RespBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

@Api(tags = "LoginController")
@RestController
public class LoginController {

    @Autowired
    private IAdminService adminService;

    @ApiOperation(value = "登入后返回token")
    @PostMapping(value = "/login")
    public RespBean login(@RequestBody AdminLoginParam adminLoginParam, HttpServletRequest request){
        return adminService.login(adminLoginParam.getUsername(),adminLoginParam.getPassword(),adminLoginParam.getCode(),request);
    }

    @ApiOperation(value = "获取当前用户信息")
    @GetMapping(value = "/admin/info")
    public Admin getAdminInfo(Principal principal){ // Authentication 接口继承 Principal 接口,UsernamePasswordAuthenticationToken 是 Authentication 实现类，Principal 代表用户登入信息
        if(null == principal){
            return null;
        }
        String username = principal.getName(); // 用户名
        Admin admin = adminService.getAdminByUsername(username); // 通过用户名查找用户
        admin.setPassword(null); // 防止用户密码泄露，设置为null
        admin.setRoles(adminService.getRoles(admin.getId()));
        return admin;
    }


    /**
     *  1.使当前 Session失效
     *  2.清除与当前用户相关的 remember-me记录
     *  3.清空当前的 SecurityContext(上下文)
     *  4.重定向到登陆页面
     */
    @ApiOperation(value = "退出登入")
    @PostMapping(value = "/logout")
    public RespBean logout(){ // 这里采用spring security 默认退出登录接口 logout
        return RespBean.success("注销成功!");
    }
}
